import { useRouter } from 'next/router'
import { RouterButton } from '../../../components'
import { getCurrentTime } from '../../../lib'

export default function Page(props:any) {
  const router = useRouter()

  if (router.isFallback) {
    return (
      <h1>Loading....</h1>
    )
  }
  else return (
    <main>
      <h1>Posts Details Page {props.id}</h1>
      <h6>{props.dt}</h6>
      <RouterButton />
      { !!props.data?.id && 
        <>
          <h4>{props.data.title}</h4>
          <br />
          <p>{props.data.body}</p>
        </>
      }
    </main>
  )
}

export async function getStaticPaths() {
  // const response = await fetch('https://dummyjson.com/posts')
  // const reply = await response.json()
  return {
    paths: [
      { params: { postId: '1' } },
      { params: { postId: '2' } },
    ],
    // paths: reply.posts.map((p:any) => ({
    //   params: { postId: p.id.toString() }
    // })),
    fallback: true,
  }
}

export async function getStaticProps(context:any) {
  const dt = getCurrentTime()
  const id = context.params.postId;

  const response = await fetch(`https://dummyjson.com/posts/${id}`)
  const reply = await response.json()

  return ({
    props: {
      dt,
      data: reply,
    }
  })
}
